package com.mspbots.core.wise.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mspbots.core.AbstractBaseServiceImpl;
import com.mspbots.core.wise.mapper.TenantUserWorkScheduleMapper;
import com.mspbots.core.wise.mapper.UsersMapper;
import com.mspbots.core.wise.model.TenantUserWorkSchedule;
import com.mspbots.core.wise.model.Users;
import com.mspbots.core.wise.model.dto.TenantUserWorkScheduleDTO;
import com.mspbots.core.wise.service.TenantUserWorkScheduleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * com.mspbots.core.wise.service.impl.TenantUserWorkScheduleServiceImpl
 *
 * @author Jason
 * @date 2020/4/29
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantUserWorkScheduleServiceImpl extends AbstractBaseServiceImpl<TenantUserWorkScheduleMapper, TenantUserWorkSchedule> implements TenantUserWorkScheduleService {

    @Autowired
    private UsersMapper usersMapper;

    @Transactional
    @Override
    public Boolean saveOneUser(TenantUserWorkScheduleDTO tenantUserWorkScheduleDTO) {
        Users users = new Users();
        users.setTimezoneFull(tenantUserWorkScheduleDTO.getTimezoneFull());
        users.setTimezoneOffset(tenantUserWorkScheduleDTO.getTimezoneOffset());
        users.setTimezoneShort(tenantUserWorkScheduleDTO.getTimezoneShort());
        usersMapper.update(users, Wrappers.<Users>lambdaUpdate().eq(Users::getTenantId, tenantUserWorkScheduleDTO.getTenantId()).eq(Users::getId, tenantUserWorkScheduleDTO.getUserId()));
        List<TenantUserWorkSchedule> saveList = tenantUserWorkScheduleDTO.getWorkScheduleList().stream().map(item -> {
            item.setUserId(tenantUserWorkScheduleDTO.getUserId());
            item.setTenantId(tenantUserWorkScheduleDTO.getTenantId());
            if (ObjectUtils.isEmpty(item.getId())) {
                item.setCreateTime(LocalDateTime.now());
            } else {
                item.setUpdateTime(LocalDateTime.now());
            }
            return item;
        }).collect(Collectors.toList());
        return saveOrUpdateBatch(saveList);
    }

    @Override
    public Boolean saveBatchUsers(List<TenantUserWorkScheduleDTO> tenantUserWorkScheduleDTOs) {
        Boolean result = true;
        for (TenantUserWorkScheduleDTO item : tenantUserWorkScheduleDTOs) {
            result = saveOneUser(item) && result;
        }
        return result;
    }

    @Override
    public IPage userPage(Page<TenantUserWorkScheduleDTO> page, TenantUserWorkSchedule queryParams) {
        Page<Users> userPage = new Page();
        userPage.setCurrent(page.getCurrent());
        userPage.setSize(page.getSize());
        userPage = usersMapper.selectPage(userPage, Wrappers.<Users>lambdaQuery()
                .select(Users::getId, Users::getTenantId, Users::getFirstName, Users::getLastName, Users::getTimezoneFull, Users::getTimezoneShort, Users::getTimezoneOffset)
                .eq(!ObjectUtils.isEmpty(queryParams.getUserId()), Users::getId, queryParams.getUserId())
                .eq(Users::getTenantId, queryParams.getTenantId())
                .eq(Users::getEnabled, true));
        List<TenantUserWorkScheduleDTO> resultList = userPage.getRecords().parallelStream().map(user -> {
            TenantUserWorkScheduleDTO tenantUserWorkScheduleDTO = TenantUserWorkScheduleDTO.builder().build();
            BeanUtils.copyProperties(user, tenantUserWorkScheduleDTO);
            tenantUserWorkScheduleDTO.setUsername(user.getFirstName() + " " + user.getLastName());
            tenantUserWorkScheduleDTO.setUserId(user.getId());
            return tenantUserWorkScheduleDTO;
        }).map(item -> {
            List<TenantUserWorkSchedule> list = list(Wrappers.<TenantUserWorkSchedule>lambdaQuery().eq(TenantUserWorkSchedule::getUserId, item.getUserId()).eq(TenantUserWorkSchedule::getTenantId, item.getTenantId()));
            item.setWorkScheduleList(list);
            ObjectNode objectNode = objectMapper.createObjectNode();
            list.forEach(workSchedule -> objectNode.put(workSchedule.getDayOfWeek(), (workSchedule.getBeginTime() + " - " + workSchedule.getEndTime()).replace("null", "")));
            item.setWorkSchedule(objectNode);

            return item;
        }).collect(Collectors.toList());
        BeanUtils.copyProperties(userPage, page);
        page.setRecords(resultList);
        return page;
    }

    @Override
    public List<TenantUserWorkScheduleDTO> findUserSchedule(Long tenantId) {
        return this.baseMapper.findUserSchedule(tenantId);
    }
}
